//
//  HotDeatilViewController.m
//  礼物go
//
//  Created by dllo on 16/5/23.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "HotDeatilViewController.h"
#import "HotDetailUpTableViewCell.h"
#import "HotDetailModel.h"
#import "HotDetailDownTableViewCell.h"
#import "LYNOTimerScrollView.h"
#import "LYCycleScrollView.h"

#import "TaoBaoViewController.h"

#import "LoginViewController.h"
#import <MBProgressHUD.h>

static NSString *const HotDetailUpCell = @"hotDetailUpCell";
static NSString *const HotDetailDownCell = @"hotDetailDownCell";

@interface HotDeatilViewController ()<UITableViewDataSource,UITableViewDelegate, UMSocialUIDelegate>

@property(nonatomic,strong)UITableView *detailTableView;

@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)HotDetailModel *hotDetailM;

@property(nonatomic,assign)CGFloat webCellHeight;

@property(nonatomic,strong)UIView *headerView;

@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIView *shareView;
@property(nonatomic,strong)UIButton *likeButton;
@property(nonatomic,strong)UIButton *taoBaoButton;


@end

@implementation HotDeatilViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   // self.view.backgroundColor = [UIColor whiteColor];
   [self setUpNavigationController];
    self.navigationController.interactivePopGestureRecognizer.enabled = YES; 
    
    self.dataArray = [NSMutableArray array];
    
    self.detailTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHeight - 49) style:UITableViewStylePlain];
    self.detailTableView.dk_backgroundColorPicker = DKColorPickerWithRGB(0xFFFAFA,0xBEBEBE);
    [self.view addSubview:self.detailTableView];
    self.detailTableView.dataSource = self;
    self.detailTableView.delegate = self;
    self.detailTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
  [self.detailTableView registerClass:[HotDetailUpTableViewCell class] forCellReuseIdentifier:HotDetailUpCell];
    [self.detailTableView registerClass:[HotDetailDownTableViewCell class] forCellReuseIdentifier:HotDetailDownCell];
    
    [self getFirstCellData];
    [self setUpBottomVew];
    
    
   //cell 自适应高度
//    self.detailTableView.estimatedRowHeight = 170;
    //self.detailTableView.rowHeight = UITableViewAutomaticDimension;
    
    
    
    
    // Do any additional setup after loading the view.
}

-(void)getFirstCellData{
    NSString *urlStr = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/items/%@",self.dataId];
    [LYNetworking ly_GetWithURL:urlStr Parameter:nil success:^(id result) {
        NSDictionary *dataDic = [result objectForKey:@"data"];
        self.hotDetailM = [[HotDetailModel alloc] init];
        [self.hotDetailM setValuesForKeysWithDictionary:dataDic];
       // NSLog(@"%@",self.hotDetailM.name);
        [self.detailTableView reloadData];

         [self getTableHeaderView];
         [self.taoBaoButton setTitle:self.hotDetailM.button_title forState:UIControlStateNormal];
        
    } error:^(NSError *error) {
        
        
    }];
}

//设置导航栏
-(void)setUpNavigationController{
    self.navigationItem.title = @"礼物详情";
   // self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Arial" size:20],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:  UIBarButtonSystemItemReply target:self action:@selector(leftButtonAction)];
   // [self.navigationItem.leftBarButtonItem setTintColor:[UIColor whiteColor]];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:  UIBarButtonSystemItemAction target:self action:@selector(rightButtonAction)];
    //[self.navigationItem.rightBarButtonItem setTintColor:[UIColor whiteColor]];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
   //self.navigationController.navigationBar.barStyle=UIBarStyleDefault;
    self.navigationController.navigationBar.translucent = NO;
    //[self.navigationController.navigationBar setBackgroundImage:[self setImageWithAlpha:1] forBarMetrics:UIBarMetricsDefault];
    
   // [self scrollViewDidScroll:self.detailTableView];

}

//设置导航条背景透明度
-(UIImage *)setImageWithAlpha:(CGFloat)alpha{
    UIColor *color = [UIColor colorWithRed:1 green:0 blue:0 alpha:alpha];
    
    CGSize colorSize=CGSizeMake(1, 1);
    
    UIGraphicsBeginImageContext(colorSize);
    //设置上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
//补充当前填充颜色的rect
    CGContextFillRect(context, CGRectMake(0, 0, 1, 1));
    //对图片放大缩小的功能
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //滑动则导航栏不为透明
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    //透明度变化值
    //CGFloat alpha = scrollView.contentOffset.y / 90.0f > 1.0f ? 1 : scrollView.contentOffset.y / 90.0f;
    
   // [self.navigationController.navigationBar setBackgroundImage:[self setImageWithAlpha:alpha] forBarMetrics:UIBarMetricsDefault];
  }

-(void)setUpBottomVew{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *userName = [user objectForKey:@"userName"];
    
  self.bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREENHeight - 49 - 64, SCREENWIDTH, 49)];
    self.bottomView.dk_backgroundColorPicker = DKColorPickerWithRGB(0xFFFAFA,0xBEBEBE);
    [self.view addSubview:self.bottomView];
    
    self.likeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.likeButton.dk_backgroundColorPicker = DKColorPickerWithRGB(0xFFFAFA,0x1C1C1C);
    self.likeButton.frame = CGRectMake(20, 5, 120, 36);
    [self.bottomView addSubview:self.likeButton];
    [self.likeButton addTarget:self action:@selector(likeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.likeButton.layer.masksToBounds = YES;
    self.likeButton.layer.cornerRadius = 15;
    self.likeButton.layer.borderWidth = 1;
    self.likeButton.layer.borderColor = [[UIColor redColor] CGColor];
    //[self.likeButton setImage:[UIImage imageNamed:@"content-details_like_16x16_@2x"] forState:UIControlStateNormal];
    [self.likeButton setTitle:@"喜欢" forState:UIControlStateNormal];
    self.likeButton.titleLabel.font = [UIFont systemFontOfSize:18];
    [self.likeButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        //NSLog(@"%d", [[DataFMDBHandle shareDataFMDBHandle] selectDataWithmyId:self.dataId]);
    self.likeButton.selected = [[DataFMDBHandle shareDataFMDBHandle] selectDataWithmyId:self.dataId WithAccount:userName];
    
    [self.likeButton setImage:[UIImage imageNamed:@"content-details_like_16x16_@2x"] forState:UIControlStateNormal];
    [self.likeButton setImage:[UIImage imageNamed:@"content-details_like_selected_16x16_@2x"] forState:UIControlStateSelected];

//    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
//    NSString *string = [user objectForKey:@"status"];
//    NSString *name = [user objectForKey:@"userName"];
   
    
//        if ([array containsObject:self.hotDetailM.name]) {
//            _likeButton.selected = YES;
//            
//        }else{
//            _likeButton.selected = NO;
//    }
    
    
    self.taoBaoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.taoBaoButton.frame = CGRectMake(160, 5, 200, 36);
    [self.bottomView addSubview:self.taoBaoButton];
    [self.taoBaoButton addTarget:self action:@selector(taoBaoButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.taoBaoButton.layer.masksToBounds = YES;
    self.taoBaoButton.layer.cornerRadius = 15;
    self.taoBaoButton.layer.borderWidth = 1;
    self.taoBaoButton.layer.borderColor = [[UIColor redColor] CGColor];
    
   
    self.taoBaoButton.titleLabel.font = [UIFont systemFontOfSize:18];
    self.taoBaoButton.dk_backgroundColorPicker = DKColorPickerWithRGB(0xFF0000,0x1C1C1C);
    self.taoBaoButton.titleLabel.textColor = [UIColor whiteColor];
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
 

    
}



-(void)likeButtonAction:(UIButton *)button{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *userName = [user objectForKey:@"userName"];
    NSString *string = [user objectForKey:@"status"];

    if (![string isEqualToString:@"yes"]) {
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        [self presentViewController:loginVC animated:YES completion:^{
            
            
        }];
        
    }else if ([[DataFMDBHandle shareDataFMDBHandle] selectDataWithmyId:self.dataId WithAccount:userName]){
        [[DataFMDBHandle shareDataFMDBHandle] deleteHotcolumn:userName myId:self.dataId];
        
        
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"取消喜欢";
        [hud showAnimated:YES whileExecutingBlock:^{
            sleep(2);
            
        } completionBlock:^{
            [hud removeFromSuperview];
            
        }];
        
        button.selected = !button.selected;
    }else{
        [[DataFMDBHandle shareDataFMDBHandle] insertHotColumn:_hotDetailM WithAccount:userName];
        
        
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"喜欢成功";
        [hud showAnimated:YES whileExecutingBlock:^{
            sleep(2);
            
        } completionBlock:^{
            [hud removeFromSuperview];
            
        }];
        
        button.selected = !button.selected;
        
    }

    
    CAKeyframeAnimation *keyAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
    keyAnimation.values = @[@(0.5),@(1.0),@(1.2)];
    keyAnimation.duration = 0.3;
    [self.likeButton.layer addAnimation:keyAnimation forKey:@"buttonlikekey"];
    
    
}

-(void)taoBaoButtonAction:(UIButton *)button{
    TaoBaoViewController *taoBaoVC = [[TaoBaoViewController alloc] init];
    taoBaoVC.urlString = self.hotDetailM.purchase_url;
    [self.navigationController pushViewController:taoBaoVC animated:YES];
    
}


-(void)setUpShareView{

}

-(void)rightButtonAction{
    //分享第二步
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"558936d367e58eb81b001298"
                                      shareText:@"欢迎使用礼物GO"
                                     shareImage:[UIImage imageNamed:@"box_01"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren, UMShareToDouban,nil]
                                       delegate:self];
}

-(void)leftButtonAction{
    [self.navigationController popViewControllerAnimated:YES];
}

//-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//    if (section == 0) {
//        
//    }
//    self.headerView = [[UIView alloc] init];
//    self.recommendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    self.recommendBtn.frame = CGRectMake(0, 0, self.headerView.frame.size.width / 2, self.headerView.frame.size.height);
//    [self.headerView addSubview:self.recommendBtn];
//    [self.recommendBtn addTarget:self action:@selector(recommendBtnAction:) forControlEvents:UIControlEventTouchUpInside];
//    
//    self.commentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    self.commentBtn.frame = CGRectMake(self.headerView.frame.size.width / 2, 0, self.headerView.frame.size.width / 2, self.headerView.frame.size.height);
//    [self.headerView addSubview:self.commentBtn];
//    [self.commentBtn addTarget:self action:@selector(commentBtnAction:) forControlEvents:UIControlEventTouchUpInside];
//    return self.headerView;
//}



-(void)getTableHeaderView{
    
    LYNOTimerScrollView *headerScroll = [[LYNOTimerScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 240)];
    NSMutableArray *array = [NSMutableArray arrayWithArray:self.hotDetailM.image_urls];
   [headerScroll setImages:array];
    self.detailTableView.tableHeaderView = headerScroll;
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0;
    }
    return 20;
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        HotDetailUpTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HotDetailUpCell];
        cell.hotDetail = self.hotDetailM;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
       // cell.backgroundColor = [UIColor yellowColor];
    return cell;
    }
   
    
   HotDetailDownTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HotDetailDownCell];
    cell.hotTableView = tableView;
    cell.hotDetailM = self.hotDetailM;
    
    __block HotDeatilViewController *hotdetail = self;

    cell.webBlockHeight = ^(CGFloat height){
        //NSLog(@"121111111====%f",self.webCellHeight);

            if (self.webCellHeight == 0 || self.webCellHeight == 44) {
//                NSLog(@"0-09008979%f",self.webCellHeight);
//                NSLog(@"66666 666   %f",height);

                hotdetail.webCellHeight = height;

                [tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];

            }
        
        
    };
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        HotDetailUpTableViewCell *cell = [HotDetailUpTableViewCell new];
      return [cell getHeightForCellByModel:self.hotDetailM] + 10;

    }
//    if (self.webCellHeight) {
//      //  NSLog(@"%f",self.webCellHeight);
//        return self.webCellHeight;
//    }
  //  NSLog(@"======sdfsda ");

    return self.webCellHeight + 49;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
